package solution8;

public class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) return 0;
        int n = str.length();
//        if (n == 0) return 0; // 空串

        // 忽略前缀空格
//        str = str.trim();
        int i = 0;

        while (i < n && str.charAt(i) == ' ') {
            i++;
        }

        if (i >= n) return 0;

        int max = Integer.MAX_VALUE;
        int min = Integer.MIN_VALUE;
        int signal = 1;

        // 处理+、-号
        if (str.charAt(i) == '+' || str.charAt(i) == '-') {
            signal = str.charAt(i) == '+' ? 1 : -1;
            ++i;
        }

        long sum = 0;
        while (i < n) {
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                sum = sum * 10 + signal * (str.charAt(i) - '0');
            }
            else {
                return (int)sum;
            }

            if (sum > max || sum < min) {
                return sum > 0 ? max : min; // 返回0 还是最大最小值？
            }

            ++i;
        }
        return (int)sum;
    }

    public static int myAtoi2(String str) {
        if (str == null || str.length() == 0)
            return 0;
        str = str.trim();
        char firstChar = str.charAt(0);
        int sign = 1, start = 0, len = str.length();
        long sum = 0;
        if (firstChar == '+') {
            sign = 1;
            start++;
        } else if (firstChar == '-') {
            sign = -1;
            start++;
        }
        for (int i = start; i < len; i++) {
            if (!Character.isDigit(str.charAt(i)))
                return (int) sum * sign;
            sum = sum * 10 + str.charAt(i) - '0';
            if (sign == 1 && sum > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            if (sign == -1 && (-1) * sum < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
        }

        return (int) sum * sign;
    }

}
